<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="返工编号" prop="reworkCode">
        <el-input
          v-model="queryParams.reworkCode"
          placeholder="请输入返工编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="返工名称？" prop="reworkName">
        <el-input
          v-model="queryParams.reworkName"
          placeholder="请输入返工名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="产品编号" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />  
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 返工日期区间 -->
      <el-form-item label="返工日期区间">
        <el-date-picker
          v-model="reworkDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- v-hasPermi="['mes:wm:rtvendor:edit']" -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rtvendorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />      
       <el-table-column label="返工单号" width="130px" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleViewDetail(scope.row)"
          >{{scope.row.reworkCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" width="150px" align="center" prop="itemName" />
      <el-table-column label="问题分类" align="center" prop="issueType" :show-overflow-tooltip="true" />
      <el-table-column label="问题描述" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="质检人员" align="center" prop="inspectorName" />
      <el-table-column label="维修方案" align="center" prop="reworkScheme" :show-overflow-tooltip="true" />
      <el-table-column label="维修人员" align="center" prop="repairer" />
      <el-table-column label="维修时间" align="center" prop="reworkTime" width="180" />
      <el-table-column label="单据状态" align="center" prop="statusDesc">
        <!-- <template slot-scope="scope">
          状态。PREPARE-草稿，FINISHED-完成
          <span v-if="scope.row.status == 'PREPARE'">草稿</span>
          <span v-if="scope.row.status == 'FINISHED'">完成</span>
          <span v-else>{{ scope.row.status }}</span>
        </template> -->
      </el-table-column>  
      <el-table-column label="关联生产工单编号" width="170" align="center" prop="taskCode" :show-overflow-tooltip="true"/>
      <el-table-column label="电池编码" width="170" align="center" prop="planCode" :show-overflow-tooltip="true"/>
      <el-table-column label="生产工单" width="170" align="center" prop="workOrderCode" :show-overflow-tooltip="true"/>       
      <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            v-if="scope.row.status =='PREPARE'"
            @click="handleExecute(scope.row)"
          >执行退货</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.status =='PREPARE'"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.status =='PREPARE'"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修单对话框 -->
    <el-dialog destroy-on-close :title="title" :close-on-click-modal="false" :visible.sync="open" width="960px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="返工单号" prop="reworkCode">
              <el-input v-model="form.reworkCode" :disabled="form.id" placeholder="请输入返工单号" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item  label-width="80">
              <el-switch 
                :disabled="form.reworkCode != null"
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                v-if="optType != 'view'"
                @change="handleAutoGenChange(autoGenFlag)" >               
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider  content-position="left">检验信息</el-divider> 
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产工单" prop="taskCode">
              <el-input v-model="form.taskCode" readonly="readonly" placeholder="请选择生产工单" >
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
              </el-input>
              <ProTaskSelect ref="vendorSelect" v-if="showItemSelect" @closeSelect="closeSelect" @onSelected="onworkerOrderSelected" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检验人员" prop="inspectorName">
              <el-input v-model="form.inspectorName" placeholder="请输入检验人员" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检验日期" prop="inspectTime">
              <el-date-picker
                v-model="form.inspectTime"
                type="datetime"
                placeholder="请选择检验日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品编码" prop="itemCode">
              <el-input 
                v-model="form.itemCode"
                placeholder="自动获取"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="itemName">
              <el-input 
                v-model="form.itemName"
                placeholder="自动获取"
                disabled
              />
            </el-form-item>
          </el-col>
          <!-- todo: 电池编码接口字段 -->
          <el-col :span="8">
            <el-form-item label="电池编码" prop="planCode">
              <el-input v-model="form.planCode" placeholder="请输入电池编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="问题分类" required prop="issueType">
              <el-select v-model="form.issueType" placeholder="请选择问题分类">
                <el-option label="极耳虚焊" value="极耳虚焊" />
                <el-option label="保护板故障" value="保护板故障" />
                <el-option label="接线问题" value="接线问题" />
                <el-option label="误判误退" value="误判误退" />
                <el-option label="电芯问题" value="电芯问题" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="问题描述" required prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left" style="font-size: 18px;">维修内容</el-divider> 
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修方案" required prop="reworkScheme">
              <el-input 
                v-model="form.reworkScheme"
                placeholder="请输入维修方案"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="物料选择" required prop="reworkLineList">
              <el-input 
                :value="reworkLineList && reworkLineList.length > 0 ? reworkLineList.map(item => item.itemName).join(',') : ''" 
                readonly="readonly" 
                placeholder="请选择物料"
                @click="handleSelectItem">
                <el-button slot="append" @click="handleSelectItem" icon="el-icon-search"></el-button>
              </el-input>
              <ItemSelect ref="itemSelect" @onSelected="onItemSelected" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 选中物料的数据展示并支持数量输入 -->
        <el-row v-if="form.reworkLineList && form.reworkLineList.length > 0">
          <el-table :data="form.reworkLineList" style="width: 96%;margin: 0px 0px 20px 23px;"> 
            <el-table-column prop="itemCode" label="物料编码" />
            <el-table-column prop="itemName" label="物料名称"  />
            <el-table-column prop="reworkCount" label="维修数量" >
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.reworkCount" placeholder="请输入维修数量" type="number" min="0" @input="handleInput(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteReworkLine(scope.$index)"
                  style="color: #f56c6c;"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="维修人员" prop="repairer">
              <el-input v-model="form.repairer" placeholder="请输入维修人员" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修时间" prop="reworkTime">
              <el-date-picker
                v-model="form.reworkTime"
                type="datetime"
                placeholder="请选择维修时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修结果" required prop="reworkResult">
              <el-select v-model="form.reworkResult" placeholder="请选择维修结果">
                <el-option
                  v-for="dict in dict.type.fix_result_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="维修数量" prop="reworkCount">
              <el-input v-model="form.reworkCount" disabled placeholder="物料信息补充完善后，自动计算" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <div slot="footer" class="dialog-footer" v-if="optType !== 'view'">
        <!-- <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button> -->
        <el-button type="primary" @click="submitForm('submit')">提 交</el-button>      
        <el-button type="primary" @click="submitForm('save')" >保 存</el-button>        
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 返工单详情弹窗 -->
    <el-dialog title="返工单详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="返工单号">{{ detailForm.reworkCode }}</el-descriptions-item>
        <el-descriptions-item label="生产工单">{{ detailForm.taskCode }}</el-descriptions-item>
        <el-descriptions-item label="检验人员">{{ detailForm.inspectorName }}</el-descriptions-item>
        <el-descriptions-item label="检验日期">{{ detailForm.inspectTime }}</el-descriptions-item>
        <el-descriptions-item label="产品编码">{{ detailForm.itemCode }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ detailForm.itemName }}</el-descriptions-item>
        <el-descriptions-item label="问题分类">{{ detailForm.issueType }}</el-descriptions-item>
        <el-descriptions-item label="问题描述">{{ detailForm.remark }}</el-descriptions-item>
        <el-descriptions-item label="维修方案">{{ detailForm.reworkScheme }}</el-descriptions-item>
        <el-descriptions-item label="维修人员">{{ detailForm.repairer }}</el-descriptions-item>
        <el-descriptions-item label="维修时间">{{ detailForm.reworkTime }}</el-descriptions-item>
        <el-descriptions-item label="维修结果">{{ detailForm.reworkResult }}</el-descriptions-item>
        <el-descriptions-item label="维修数量">{{ detailForm.reworkCount }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 物料信息 -->
      <el-divider content-position="left" style="font-size: 18px;margin-top: 30px;">物料信息</el-divider>
      <el-table :data="detailForm.reworkLineList" style="width: 100%;" max-height="300">
        <el-table-column prop="itemCode" label="物料编码" />
        <el-table-column prop="itemName" label="物料名称" />
        <el-table-column prop="reworkCount" label="维修数量" />
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { getRepairList, getRepairDetail, deleteRepair, addRepair, updateRepair } from "@/api/mes/pro/repair";
import {genCode} from "@/api/system/autocode/rule"
import ProTaskSelect from "@/components/ProTaskSelect/single.vue";
import ItemSelect from "@/components/itemSelect/index.vue";

import { listPurchaseOrder, getListConfirmed } from "@/api/mes/pro/purchaseOrder";
export default {
  name: "Rtvendor",
  components:{ProTaskSelect, ItemSelect},
  dicts: ['mes_order_status', 'fix_result_type'],
  data() {
    return {
      //自动生成编码
      autoGenFlag:false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修单表格数据
      rtvendorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reworkCode: null,
        reworkName: null,
        itemCode: null,
        itemName: null,
        endTime: null,
        startTime: null,
      },
      // 结束时间为昨天，开始时间为昨天之前的30天
      reworkDate: [
        this.getLastMonth(),
        this.getYesterday()
      ],
      // 表单参数
      form: {
        reworkCode: null,
        taskCode: null,
        inspectorName: this.$store.state.user.name,
        inspectTime: null,
        reworkScheme: null,
        reworkLineList: null,
        reworkCount: null,
        reworkResult: null,
        reworkTime: null,
        remark: null,
        issueType: null,
        repairer: this.$store.state.user.name,

      },
      // 表单校验
      rules: {
        reworkCode: [
          { required: true, message: "返工单号编码不能为空", trigger: "blur" }
        ],
        // taskCode: [
        //   { required: true, message: "生产工单不能为空", trigger: "blur" }
        // ],
        issueType: [
          { required: true, message: "问题类型不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "问题描述不能为空", trigger: "blur" }
        ],
        reworkScheme: [
          { required: true, message: "维修方案不能为空", trigger: "blur" }
        ],
        reworkLineList: [
          { 
            validator: function(rule, value, callback) {
              if (!value || value.length === 0) {
                callback(new Error('请选择物料'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ],
        repairer: [
          { required: true, message: "维修人员不能为空", trigger: "blur" }
        ],
        reworkTime: [
          { required: true, message: "维修时间不能为空", trigger: "blur" }
        ],
        reworkResult: [
          { required: true, message: "维修结果不能为空", trigger: "blur" }
        ],


      },
      poList: [],
      showItemSelect: true, // 是否显示物料选择组件
      
      // 详情弹窗表单参数
      detailForm: {
        reworkCode: null,
        taskCode: null,
        inspectorName: null,
        inspectTime: null,
        reworkScheme: null,
        reworkLineList: [],
        reworkCount: null,
        reworkResult: null,
        reworkTime: null,
        remark: null,
        issueType: null,
        repairer: null,
        itemCode: null,
        itemName: null,
      },
      // 是否显示详情弹窗
      detailOpen: false,
    };
  },
  created() {
    this.getList();
    //todo: :'not_in', 2025年3月14日14:10:05
    getListConfirmed({pageNum:1, pageSize:9999, }).then(response => {
      this.poList = response.rows;
    });
  },
  watch: {
    'form.reworkLineList': {
      handler(newVal, oldVal) {
        if(newVal && newVal.length > 0){
          let count = 0;
          newVal.forEach(item => {
            count += item.reworkCount ? Number(item.reworkCount) : 0;
          });
          this.form.reworkCount = count || 0;
        }
      },
      deep: true
    }
  },
  methods: {
     async handleViewDetail(row) {
    const id = row?.id;
    if (!id) return this.$message.error('记录缺少 id');

    try {
      
      // this.detailLoading = true;      // 可在 dialog 内加 v-loading="detailLoading"

      const { data } = await getRepairDetail(id);

      // 兼容后端字段名，确保数组存在
      const lines = Array.isArray(data.reworkLineList)
        ? data.reworkLineList
        : (typeof data.reworkLineList === 'string'
            ? JSON.parse(data.reworkLineList || '[]')  // 若后端返回 JSON 字符串
            : []);

      this.detailForm = {
        reworkCode: data.reworkCode,
        taskCode: data.taskCode,
        inspectorName: data.inspectorName,
        inspectTime: data.inspectTime,
        itemCode: data.itemCode,
        itemName: data.itemName,
        issueType: data.issueType,
        remark: data.remark,
        reworkScheme: data.reworkScheme,
        repairer: data.repairer,
        reworkTime: data.reworkTime,
        reworkResult: data.reworkResult,
        reworkCount: data.reworkCount,
        reworkLineList: lines
      };
      this.detailOpen = true;         // 先打开弹窗，也可先 loading
    } catch (e) {
      this.$message.error('获取详情失败');
      this.detailOpen = false;
    } finally {
      // this.detailLoading = false;
    }
  },
    // 获取昨天的日期
    getYesterday() {
      const date = new Date();
      date.setDate(date.getDate());
      return date.toISOString().split('T')[0];
    },
    // 获取昨天之前的30天的日期
    getLastMonth() {
      const date = new Date();
      date.setDate(date.getDate() - 30);
      return date.toISOString().split('T')[0];
    },


    /** 查询维修单列表 */
    getList() {
      this.loading = true;
      if(this.reworkDate && this.reworkDate.length > 0){
        this.queryParams.startTime = this.reworkDate[0];
        this.queryParams.endTime = this.reworkDate[1];
      }else{
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;

      }
      getRepairList(this.queryParams).then(response => {
        this.rtvendorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.autoGenFlag = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reworkCode: null,
        taskCode: null,
        inspectorName: this.$store.state.user.name,
        inspectTime: null,
        reworkScheme: null,
        reworkLineList: [],
        reworkCount: null,
        reworkResult: null,
        reworkTime: null,
        remark: null,
        issueType: null,
        repairer: this.$store.state.user.name
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.reworkDate = [
        this.getLastMonth(),
        this.getYesterday()
      ];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修单";
      this.optType = "add";
      this.autoGenFlag = true;
      this.handleAutoGenChange(true);
      this.form.repairer = this.$store.state.user.name;
      this.form.reworkTime = new Date().toISOString().replace('T', ' ').substring(0, 19); 
    },
    // 查询明细按钮操作
    handleView(row){
      this.reset();
      const rtIds = row.id
      getRepairDetail(rtIds).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看维修单";
        this.optType = "view";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRepairDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改维修单";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 提交时，手动将状态改为完成
          if(type == 'submit'){
            this.form.status = 'FINISHED';
          }
          if (this.form.id != null) {
            updateRepair(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRepair(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //执行退货
    handleExecute(row){
      const rtIds = row.id || this.ids;
      this.$modal.confirm('确认执行退货？').then(function() {
        return execute(rtIds)//执行入库
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("退货成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rtIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除维修单编号为"' + rtIds + '"的数据项？').then(function() {
        return deleteRepair(rtIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/rtvendor/export', {
        ...this.queryParams
      }, `rtvendor_${new Date().getTime()}.xlsx`)
    },
    // 工单选择
    handleSelectVendor(){
      this.$refs.vendorSelect.showFlag = true;
    },
    //物料选择
    handleSelectItem(){
      // 清除验证错误，避免打开弹窗时显示验证提示
      this.$refs.form.clearValidate('reworkLineList');
      this.$refs.itemSelect.showFlag = true;
    },
    //工单选择
    onworkerOrderSelected(obj){
        if(obj != undefined && obj != null){
          this.form.taskCode = obj.taskCode; //工单编码
          this.form.taskId = obj.taskId; // 工单ID

          // this.form.inspectTime = obj.requestDate; // 检验日期
          this.form.itemCode = obj.itemCode; // 产品编码
          this.form.itemName = obj.itemName; // 产品名称
          this.form.itemId = obj.itemId; // 产品ID
          this.closeSelect();
        }
    },
    //物料选择
    onItemSelected(obj){
      if(obj != undefined && obj != null){
        // 新增的数据reworkCount默认为0
        obj.forEach(item => {
          this.$set(item, 'reworkCount', 0)
        })

        const newArr = this.form.reworkLineList != null ? [...this.form.reworkLineList, ...obj] : [...obj];
        this.form.reworkLineList = newArr.filter((item, index, arr) => {
          return arr.findIndex(t => t.itemId === item.itemId) === index
        })

        // 选择物料后清除验证错误
        this.$nextTick(() => {
          this.$refs.form.clearValidate('reworkLineList');
        });
      }
    },
    // 删除选中的reworkLineList项
    handleDeleteReworkLine(index) {
      this.$confirm('确定要删除这个物料吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 从数组中删除指定索引的项
        this.form.reworkLineList.splice(index, 1);
        // 清除并重新验证表单字段
        this.$nextTick(() => {
          this.$refs.form.clearValidate('reworkLineList');
          if (this.form.reworkLineList.length === 0) {
            this.$refs.form.validateField('reworkLineList');
          }
        });
        this.$message.success('删除成功');
      }).catch(() => {
        // 用户取消删除
      });
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('DC_REWORK_CODE').then(response =>{
          this.form.reworkCode = response;
        });
      }else{
        this.form.reworkCode = null;
      }
    },
    closeSelect(){
      this.showItemSelect = false;
      setTimeout(()=>{
        this.showItemSelect = true;
      }, 200)
    },
    
    // 处理维修数量输入，确保只能输入大于等于0的整数
    handleInput(row) {
      // 如果输入为空，设置为0
      if (row.reworkCount === '' || row.reworkCount === null || row.reworkCount === undefined) {
        row.reworkCount = 0;
        return;
      }
      
      // 转换为数字
      let value = Number(row.reworkCount);
      
      // 检查是否为数字
      if (isNaN(value)) {
        row.reworkCount = 0;
        return;
      }
      
      // 检查是否为负数
      if (value < 0) {
        row.reworkCount = 0;
        this.$message.warning('维修数量不能为负数');
        return;
      }
      
      // 确保是整数
      if (!Number.isInteger(value)) {
        row.reworkCount = Math.floor(value);
        this.$message.warning('维修数量必须为整数，已自动取整');
        return;
      }
      
      // 确保是数字类型
      row.reworkCount = value;
    }
  },
};
</script>
